package jwt

import (
	"github.com/dgrijalva/jwt-go"
	jwtmiddleware "github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris"
)

const JWT_SECRET = "1ipqDQffsut7o"

func Configurator(app *iris.Application) {
	jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(JWT_SECRET), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
	})
	// ignore login
	app.Use(func(ctx iris.Context) {
		path := ctx.Path()
		if path == "/api/user/login" {
			ctx.Next()
		} else {
			jwtHandler.Serve(ctx)
		}
	})
}

func CreateToken(data map[string]interface{}) (tokenString string) {
	claims := make(jwt.MapClaims, 0)
	for k, v := range data {
		claims[k] = v
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	s, _ := token.SignedString([]byte(JWT_SECRET))
	return s
}

func GetUser(ctx iris.Context) (data map[string]interface{}) {
	user := make(map[string]interface{}, 0)
	userToken := ctx.Values().Get("jwt").(*jwt.Token)
	if claims, ok := userToken.Claims.(jwt.MapClaims); ok && userToken.Valid {
		for k, v := range claims {
			user[k] = v
		}
	}
	return user
}
